<?php
/**
 * Created by PhpStorm.
 * User: Robin
 * Date: 2019/10/22
 * Time: 15:58
 */

namespace addons\kzvote\library;


/*
 * 此文件用于生成海报
 * 返回格式是二进制
 * */
class Poster
{

    /**
     * 创建小程序分享吗海报
     * @param array $config
     * @param string $filename
     * @param int[] $background_color
     * @return bool|void
     */
    public static function createPoster($config = array(), $filename = "", $background_color = [216, 74, 65])
    {
        ob_clean();
        if (empty($filename)) {
            header("content-type: image/jpeg");
        }

        $imageDefault = array(
            'left' => 0,
            'top' => 0,
            'right' => 0,
            'bottom' => 0,
            'width' => 100,
            'height' => 100,
            'opacity' => 100,
        );
        $textDefault = array(
            'text' => '',
            'left' => 0,
            'top' => 0,
            'fontSize' => 32, //字号
            'fontColor' => '255,255,255', //字体颜色
            'angle' => 0,
        );

        $image_count = count($config['image']);

        $backgroundWidth = 600; //背景宽度
        $backgroundHeight = 450 + ($image_count * 210) + 150; //背景高度

        $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
        $color = imagecolorallocate($imageRes, $background_color[0], $background_color[1], $background_color[2]); //默认红色背景，由前端传入
        imagefill($imageRes, 0, 0, $color);

//        $white_imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
//        $white = imagecolorallocate($white_imageRes, 255, 255, 255); //白色背景
//        imagefilledrectangle($imageRes, 30, 260, 570, $backgroundHeight - 20, $color);

        $black = imagecolorallocate($imageRes, 255, 255, 255); // 白色背景
        imagefilledellipse($imageRes,300,730,300,300,$black);

        //处理图片
        if (!empty($config['image'])) {
            foreach ($config['image'] as $key => $val) {
                if (!self::kzvote_checkFile($val['url'])){
                    continue;
                }
                $val = array_merge($imageDefault, $val);
                $info = getimagesize($val['url']);

                $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
                if ($val['stream']) { //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];

                if (isset($val['name']) && ($val['name'] == 'vote' || $val['name'] == 'person')){
                    $val['width'] = $resWidth > 540 ? 540 : $resWidth;
                    $val['height'] = $resHeight / $resWidth * $val['width'];
                    $val['height'] = $val['height'] > 400 ? 400 : $val['height'];
                }

                //建立画板 ，缩放图片至指定尺寸
                $canvas = imagecreatetruecolor($val['width'], $val['height']);
                imagefill($canvas, 0, 0, $color);

                //设置圆形
                if ($val['is_yuan']) {
                    imagesavealpha($canvas, true);

                    $r   = $val['width'] / 2; //圆半径
                    for ($x = 0; $x < $val['width']; $x++) {
                        for ($y = 0; $y < $val['height']; $y++) {
                            $rgbColor = imagecolorat($res, $x, $y);
                            if (((($x - $r) * ($x - $r) + ($y - $r) * ($y - $r)) < ($r * $r))) {
                                imagesetpixel($canvas, $x, $y, $rgbColor);
                            }
                        }
                    }
                }else{
                    //如果是透明的gif或png做透明处理
                    $ext = pathinfo($val['url']);
                    if (array_key_exists('extension', $ext)) {
                        if ($ext['extension'] == 'gif' || $ext['extension'] == 'png') {
                            imageColorTransparent($canvas, $color); //颜色透明
                        }
                    }
                    //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                    imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);
                }

                //如果left小于-1我这做成了计算让其水平居中
                if ($val['left'] < 0) {
                    $val['left'] = ceil($backgroundWidth - $val['width']) / 2;
                }
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
                //放置图像
                imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']); //左，上，右，下，宽度，高度，透明度
            }
        }
        //处理文字
        if (!empty($config['text'])) {
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault, $val);
                list($R, $G, $B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $ttf = ROOT_PATH . 'public/assets/fonts/SourceHanSansK-Regular.ttf';
                //如果left小于-1我这做成了计算让其水平居中
                if ($val['left'] < 0) {
                    $fontBox = imagettfbbox($val['fontSize'], 0, $ttf, $val['text']); //文字水平居中实质
                    $val['left'] = ceil(($backgroundWidth - $fontBox[2]) / 2); //计算文字的水平位置

                }
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
                $val['text'] = mb_convert_encoding($val['text'], "html-entities", "utf-8");
                imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $ttf, $val['text']);
            }
        }
        //生成图片
        if (!empty($filename)) {
            $res = imagejpeg($imageRes, $filename, 90); //保存到本地
            imagedestroy($imageRes);
            if (!$res) {
                return false;
            }

            return $res;
        } else {
            header("Content-type: image/jpeg");
            imagejpeg($imageRes); //在浏览器上显示
            imagedestroy($imageRes);
        }
    }

    /**
     * 创建二维码海报
     * @param array $config
     * @param string $filename
     * @param int[] $background_color
     * @return bool|void
     */
    public static function createQrPoster($config = array(), $filename = "", $background_color = [216, 74, 65])
    {
        ob_clean();

        $imageDefault = array(
            'left' => 0,
            'top' => 0,
            'right' => 0,
            'bottom' => 0,
            'width' => 100,
            'height' => 100,
            'opacity' => 100,
        );
        $textDefault = array(
            'text' => '',
            'left' => 0,
            'top' => 0,
            'fontSize' => 32, //字号
            'fontColor' => '255,255,255', //字体颜色
            'angle' => 0,
            'ttf' => 'SourceHanSansK-Regular.ttf'
        );

        $backgroundWidth = $config["size"]["width"]; //背景宽度
        $backgroundHeight = $config["size"]["height"]; //背景高度
        $imageRes = imageCreatetruecolor($backgroundWidth, $backgroundHeight);
        imagesavealpha($imageRes, true);
        /*
        $posterBgInfo = getimagesize($config["poster_bg"]);
        $function = 'imagecreatefrom' . image_type_to_extension($posterBgInfo[2], false);
        $imageRes = $function($config["poster_bg"]);
        */
        //$color = imagecolorallocate($imageRes, $background_color[0], $background_color[1], $background_color[2]); //默认红色背景，由前端传入
        $color = imagecolorallocatealpha($imageRes, $background_color[0], $background_color[1], $background_color[2], 127); //默认红色背景，由前端传入
        imagefill($imageRes, 0, 0, $color);

        //处理图片
        if (!empty($config['image'])) {
            foreach ($config['image'] as $key => $val) {
                if (!self::kzvote_checkFile($val['url'])){
                    continue;
                }
                $val = array_merge($imageDefault, $val);
                $info = getimagesize($val['url']);

                $function = 'imagecreatefrom' . image_type_to_extension($info[2], false);
                if ($val['stream']) { //如果传的是字符串图像流
                    $info = getimagesizefromstring($val['url']);
                    $function = 'imagecreatefromstring';
                }
                $res = $function($val['url']);
                $resWidth = $info[0];
                $resHeight = $info[1];

                if (isset($val['name']) && ($val['name'] == 'vote' || $val['name'] == 'person')){
                    $val['width'] = $resWidth > 540 ? 540 : $resWidth;
                    $val['height'] = $resHeight / $resWidth * $val['width'];
                    $val['height'] = $val['height'] > 400 ? 400 : $val['height'];
                }

                //建立画板 ，缩放图片至指定尺寸
                $canvas = imagecreatetruecolor($val['width'], $val['height']);
                imagefill($canvas, 0, 0, $color);
                //如果是透明的gif或png做透明处理
                $ext = pathinfo($val['url']);
                if (array_key_exists('extension', $ext)) {
                    if ($ext['extension'] == 'gif' || $ext['extension'] == 'png') {
                        imageColorTransparent($canvas, $color); //颜色透明
                    }
                }
                //关键函数，参数（目标资源，源，目标资源的开始坐标x,y, 源资源的开始坐标x,y,目标资源的宽高w,h,源资源的宽高w,h）
                imagecopyresampled($canvas, $res, 0, 0, 0, 0, $val['width'], $val['height'], $resWidth, $resHeight);

                //如果left小于-1我这做成了计算让其水平居中
                if ($val['left'] < 0) {
                    $val['left'] = ceil($backgroundWidth - $val['width']) / 2;
                }
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) - $val['height'] : $val['top'];
                //放置图像
                imagecopymerge($imageRes, $canvas, $val['left'], $val['top'], $val['right'], $val['bottom'], $val['width'], $val['height'], $val['opacity']); //左，上，右，下，宽度，高度，透明度
            }
        }
        //处理文字
        if (!empty($config['text'])) {
            foreach ($config['text'] as $key => $val) {
                $val = array_merge($textDefault, $val);
                list($R, $G, $B) = explode(',', $val['fontColor']);
                $fontColor = imagecolorallocate($imageRes, $R, $G, $B);
                $ttf = ROOT_PATH . 'public/assets/fonts/'.$val['ttf'];
                //如果left小于-1我这做成了计算让其水平居中
                if ($val['left'] < 0) {
                    $fontBox = imagettfbbox($val['fontSize'], 0, $ttf, $val['text']); //文字水平居中实质
                    $val['left'] = ceil(($backgroundWidth - $fontBox[2]) / 2); //计算文字的水平位置

                }
                $val['top'] = $val['top'] < 0 ? $backgroundHeight - abs($val['top']) : $val['top'];
                $val['text'] = mb_convert_encoding($val['text'], "html-entities", "utf-8");
                imagettftext($imageRes, $val['fontSize'], $val['angle'], $val['left'], $val['top'], $fontColor, $ttf, $val['text']);
            }
        }
        //生成图片
        if (!empty($filename)) {
            $res = imagepng($imageRes, $filename, 90); //保存到本地
            imagedestroy($imageRes);
            if (!$res) {
                return false;
            }

            return $res;
        } else {
            imagepng($imageRes); //在浏览器上显示
            imagedestroy($imageRes);
        }
    }

    //检查远程图片是否存在
    public static function kzvote_checkFile($url) {
        $curl = curl_init($url); // 不取回数据
        curl_setopt($curl, CURLOPT_NOBODY, true);
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, 'GET'); // 发送请求
        $result = curl_exec($curl);
        $found = false; // 如果请求没有发送失败
        if ($result !== false) {
            $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if ($statusCode == 200) { //再检查http响应码是否为200
                $found = true;
            }
        }
        curl_close($curl);
        return $found;
    }

}
